package respdata

import (
	"encoding/json"
	"fmt"
	"io"
)

// New godoc
// @Summary      响应
// @Description  响应返回的数据中包含以下字段：Code,Msg,Data
// @Description  Code=错误码
// @Description  Msg=错误信息
// @Description  Data=具体数据，一般成功情况下会返回对应数据
// @Tags         通用
// @Router       /-common/response [post]
// @x-code-samples [{"lang":"js","label":"成功","source":"{\n\"code\":0,\n\"msg\":\"success\",\n\"data\":{}\n}"},{"lang":"js","label":"失败","source":"{\n\"code\":1,\n\"msg\":\"error\",\n\"data\":{}\n}"}]
func New(code int64, msg string, data interface{}) ResponseData {
	return ResponseData{
		code, msg, data,
	}
}

type ResponseData struct {
	Code int64       `json:"code"` //返回码，0：成功，>0为对应错误码
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (data ResponseData) MData(d interface{}) ResponseData {
	data.Data = d
	return data
}

func (data ResponseData) MCode(code int64) ResponseData {
	data.Code = code
	return data
}

func (data ResponseData) MMsg(msg string) ResponseData {
	data.Msg = msg
	return data
}

func (data ResponseData) Error() string {
	if data.Code != 0 {
		return fmt.Sprintf("%d,%s", data.Code, data.Msg)
	}
	return "0,success"
}

func (data ResponseData) String() string {
	s, _ := json.Marshal(data)
	return string(s)
}

func ErrToResponseData(err error) ResponseData {
	if err == nil {
		return CSuccess
	}
	if d, ok := err.(ResponseData); ok {
		return d
	}
	return CError.MMsg(err.Error())
}

func ReaderToResponseData(r io.Reader) (ResponseData, error) {
	var data ResponseData
	b, err := io.ReadAll(r)
	if err != nil {
		return data, err
	}

	if err = json.Unmarshal(b, &data); err != nil {
		return data, err
	}
	return data, nil
}
